package com.kcl.dfss.utils;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.security.MessageDigest;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Environment;



public class FTPUtils {
	public FTPUtils(){
		
	}
	
	/**
	 * ftp上传
	 * @param url	ftp地址
	 * @param port  ftp连接端口号
	 * @param username  登录用户名
	 * @param password  登录密码
	 * @param fileNamePath  本地文件保存路径
	 * @param fileName  本地文件名
	 * @return
	 */
	public static String ftpUpload(String url, String port, String username,String password, String fileNamePath,String fileName){
		 FTPClient ftpClient = new FTPClient();  
		 FileInputStream fis = null;  
		 String returnMessage = "0";  
		 try {  
		     ftpClient.connect(url, Integer.parseInt(port));  
		     boolean loginResult = ftpClient.login(username, password);  
		     int returnCode = ftpClient.getReplyCode();  
		     if (loginResult && FTPReply.isPositiveCompletion(returnCode)) {// 如果登录成功  
		         ftpClient.setBufferSize(1024);  
		         ftpClient.setControlEncoding("UTF-8");  
		         ftpClient.enterLocalPassiveMode();  
		         fis = new FileInputStream(fileNamePath + fileName);  
		         ftpClient.storeFile(fileName, fis);  
		         
		         returnMessage = "1";   //上传成功        
		     } else {// 如果登录失败  
		         returnMessage = "0";  
		     }  
		  
		 } catch (IOException e) {  
		     e.printStackTrace();  
		     throw new RuntimeException("FTP客户端出错！", e);  
		 } finally {  
		     //IOUtils.closeQuietly(fis);  
			 try {  
			     ftpClient.disconnect();  
			 } catch (IOException e) {  
			        e.printStackTrace();  
			        throw new RuntimeException("关闭FTP连接发生异常！", e);  
			 }  
		 }  
		 return returnMessage;  
	}
	
	/**
	 * ftp下载
	 * @param url
	 * @param port
	 * @param username
	 * @param password
	 * @param filePath 存放文件的路径
	 * @param FTP_file 要下载的文件名
	 * @param SD_file 本地文件名
	 */
	public static String ftpDown(String url, int port, String username,String password, String filePath,String FTP_file,String SD_file){
		BufferedOutputStream buffOut = null;
		
		FTPClient ftpClient = new FTPClient();
		String returnMessage = "0";  
		 try {  
		     ftpClient.connect(url, port);  
		     boolean loginResult = ftpClient.login(username, password);  
		     int returnCode = ftpClient.getReplyCode();  
		     if (loginResult && FTPReply.isPositiveCompletion(returnCode)) {// 如果登录成功  
		         ftpClient.setBufferSize(1024);  
		         ftpClient.setControlEncoding("UTF-8");  
		         ftpClient.enterLocalPassiveMode();  
		         
		         buffOut = new BufferedOutputStream(new FileOutputStream(filePath+SD_file),8*1024);
		         ftpClient.retrieveFile(FTP_file, buffOut);
		         buffOut.flush();
		         buffOut.close();
		         
		         ftpClient.logout();
		         ftpClient.disconnect();
		         
		         returnMessage = "1";   //上传成功        
		     } else {// 如果登录失败  
		         returnMessage = "0";  
		     }  
		  
		 } catch (IOException e) {  
		     e.printStackTrace();  
		     throw new RuntimeException("FTP客户端出错！", e);  
		 } finally {  
		     //IOUtils.closeQuietly(fis);  
			 try {  
			     ftpClient.disconnect();  
			 } catch (IOException e) {  
			        e.printStackTrace();  
			        throw new RuntimeException("关闭FTP连接发生异常！", e);  
			 }  
		 }  
		 return returnMessage;
	}
	
	/**
	 * 生成json文件并保存到sd卡
	 * @param context
	 */
	public static void saveJsonTosdCard(Context context){
		SharedPreferences preferences = context.getSharedPreferences("camcfg", 0);
		String positionX = preferences.getString("positionX", "0");
		String positionY = preferences.getString("positionY", "0");
		String positionZ = preferences.getString("positionZ", "0");
		String braid = preferences.getString("brandID", "0");
		String serid = preferences.getString("seriesID", "0");
		String modid = preferences.getString("modelID", "0");
		String tilt = preferences.getString("tilt", "0");
		String roll = preferences.getString("roll", "0");
		String pan = preferences.getString("pan", "0");
		String vehicleWidth = preferences.getString("vehicleWidth", "0");
		String version = preferences.getString("versionNum", "0");
		
		JSONObject jsonObject = new JSONObject();
		try {
			jsonObject.put("positionX", positionX);
			jsonObject.put("positionY", positionY);
			jsonObject.put("positionZ", positionZ);
			jsonObject.put("brandID", braid);
			jsonObject.put("seriesID", serid);
			jsonObject.put("modelID", modid);
			jsonObject.put("tilt", tilt);
			jsonObject.put("roll", roll);
			jsonObject.put("pan", pan);
			jsonObject.put("vehicleWidth", vehicleWidth);
			jsonObject.put("versionNum", version);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		
		String json = jsonObject.toString();
		
		File sdCareDir = Environment.getExternalStorageDirectory();
		File saveFile = new File(sdCareDir, "camcfg.json");
		try {
			FileOutputStream outStream = new FileOutputStream(saveFile);
			outStream.write(json.getBytes());
			outStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 从sd卡读取JSON文件;
	 * filename 保存在sd卡的json文件名
	 * @return
	 */
	public static String readJsonForSdcard(String filename){
		StringBuffer sb = new StringBuffer();
		try {
			File file = new File(Environment.getExternalStorageDirectory()+"/"+filename);
			InputStream in = new FileInputStream(file);
			int tempbyte;
			while((tempbyte = in.read())!= -1){
				sb.append((char)tempbyte);
			}
			in.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		String result = sb.toString();
		return result;
	}
	
	/**
	 * 生成文件MD5值
	 * @param file 文件存放路径
	 * @return
	 */
	public static String getFileMD5(File file) {
		if (!file.isFile()) {
			return null;
		}
		MessageDigest digest = null;
		FileInputStream in = null;
		byte buffer[] = new byte[1024];
		int len;
		try {
			digest = MessageDigest.getInstance("MD5");
			in = new FileInputStream(file);
			while ((len = in.read(buffer, 0, 1024)) != -1) {
				digest.update(buffer, 0, len);
			}
			in.close();
		} catch (Exception e) {
			e.printStackTrace();
			return e.toString();
		}
		BigInteger bigInt = new BigInteger(1, digest.digest());
		return bigInt.toString(16);
	}
}
